package com.lagou.provider;

import com.lagou.RpcDecoder;
import com.lagou.RpcEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;

@Component
@PropertySource("classpath:application.properties")
@ConfigurationProperties(prefix="server.provider")
public class ProviderServerBoot {

    private String ip;

    private Integer port;

    private String appName;
    @Autowired
    private RpcProcessHandler rpcProcessHandler;
    @PostConstruct
    public void init() throws Exception{
        //只有当服务器配置了server.provider属性，才会启动提供者服务器
        if ((!StringUtils.isEmpty(ip)) && port != null) {
            //1.创建两个线程池对象
            NioEventLoopGroup bossGroup = new NioEventLoopGroup();
            NioEventLoopGroup  workGroup = new NioEventLoopGroup();

            //2.创建服务端的启动引导对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            //3.配置启动引导对象
            serverBootstrap.group(bossGroup,workGroup)
                    //设置通道为NIO
                    .channel(NioServerSocketChannel.class)
                    //创建监听channel
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                            //获取管道对象
                            ChannelPipeline pipeline = nioSocketChannel.pipeline();
                            //给管道对象pipeLine 设置编码
                            pipeline.addLast(new RpcEncoder());
                            pipeline.addLast(new RpcDecoder());
                            //把我们自顶一个ChannelHander添加到通道中
                            ChannelInboundHandlerAdapter adapter = rpcProcessHandler;
                            pipeline.addLast(adapter);
                        }
                    });

            //4.绑定端口
            serverBootstrap.bind(port).sync();
        }
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getAppName() {
        return appName;
    }

    public void setAppName(String appName) {
        this.appName = appName;
    }
}
